package cn.yunyichina.provider.bone.service.impl;

import cn.yunyichina.provider.bone.dao.BoneDiagnoseDao;
import cn.yunyichina.provider.bone.entity.BoneDiagnose;
import cn.yunyichina.provider.bone.utils.BoneMsgUtils;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.*;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.iface.entity.ErrorCodeDefine;
import cn.yunyichina.provider.iface.entity.PersonalUser;
import cn.yunyichina.provider.iface.entity.PersonalUserOpenid;
import cn.yunyichina.provider.framework.dubbo.service.*;
import cn.yunyichina.provider.framework.utils.UUIDUtil;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.base.OrgApp;
import cn.yunyichina.provider.iface.entity.bone.OrderBoneExtendVo;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.pay.PaymentJournalVo;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.commons.NumberUtil;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);
    private static final String ORG_CODE = "rykj";
    private static final String ORG_ID = "ffdbc274acbd11e6990400163e0042e8";
    private static final String ORG_NAME = "广州仁医骨科科技有限公司";
    
    // 平台服务费计算比率
    private static final float PLATFORM_SERVICE_RATE = 0.15f;
    // 手术意外险 1分钱
    private static final int SURGERY_ACCIDENT_FEE = 1;
    // 押金折扣 200元
	private static final int DISCOUNT_AMOUNT = -200_00;

    @Autowired
    private BoneDiagnoseDao boneDiagnoseDao;

    /**
     * 获取订单列表 yyt.bone.order.list
     *
     * @param data
     * @return
     */
    public Response listOrder(String data) {
        Response response = new Response();

        logger.info("获取订单列表, 调用order模块, 入参request=" + data);
        Response orderRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.order.list", data);
        logger.info("获取订单列表, 调用order模块, 查询返回respone=" + JsonUtils.toJsonString(orderRespone));
        if (!orderRespone.getResultCode().equals("0")) {
            return Response.failure();
        }

        response.setResult(JsonUtils.toJsonString(orderRespone.getResult()));

        return response;
    }


    /**
     * 专家和主治医生首页未处理统计数 yyt.bone.order.info.count.get
     *
     * @param data
     * @return
     */
    public Response getOrderInfoCount(String data) {
        Response response = new Response();
        Map<String , String> param = JsonUtils.parseObject(data, Map.class);

        String doctorId = param.get("doctor_id");
        String doctorType = param.get("doctor_type");

        if(StringUtils.isBlank(doctorId) || StringUtils.isBlank(doctorType)){
            response.setResultCodeAndMessage(Response.FAILURE_CODE , "入参为空,请检查入参");
            return response;
        }

        Map<String, Object> result = new HashMap<String, Object>();
        int surUntreated = 0;
        int patUploaded = 0;

        try {
            if("1".equals(doctorType)){
                logger.info("统计专家 手术预约需处理数, 调用order模块, 入参request=" + data);
                Response orderRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.order.and.order.for.doctorid.get", data);
                logger.info("统计专家 手术预约需处理数, 调用order模块, 查询返回respone=" + JsonUtils.toJsonString(orderRespone));

                if ("0".equals(orderRespone.getResultCode())) {
                    List<Map> maps = JsonUtils.parseArray(orderRespone.getResult(), Map.class);
                    if(maps.size() > 0){
                        for (Map map : maps) {
                            String orderType = String.valueOf(map.get("orderStatus"));
                            if("91".equals(orderType)){
                                String manageStatus = String.valueOf(map.get("manageStatus"));
                                if("1".equals(manageStatus)){
                                    surUntreated ++;
                                }
                            }else if("92".equals(orderType)){
                                surUntreated ++;
                            }
                        }
                    }
                }
            }

            Map<String,String> dataMap = new HashMap<String, String>();
            dataMap.put("doctor_id" , doctorId);
            dataMap.put("doctor_type" , "2");

            logger.info("统计主治 患者资料未上传数, 调用order模块, 入参json =" + JsonUtils.toJsonString(dataMap));
            Response orderRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.order.and.order.for.doctorid.get", JsonUtils.toJsonString(dataMap));
            logger.info("统计主治 患者资料未上传数, 调用order模块, 查询返回json =" + JsonUtils.toJsonString(orderRespone));

            if ("0".equals(orderRespone.getResultCode())) {
                List<Map> maps = JsonUtils.parseArray(orderRespone.getResult(), Map.class);
                if(maps.size() > 0){
                    for (Map map : maps) {
                        String orderType = String.valueOf(map.get("orderStatus"));

                        if(!"90".equals(orderType)){
                            String uploadMethod = String.valueOf(map.get("uploadMethod"));
                            if(StringUtils.isBlank(uploadMethod) || "null".equals(uploadMethod)){
                                patUploaded ++;
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.error("[OrderServiceImpl.getOrderInfoCount]  查询异常" , e);
            response.setResultCodeAndMessage(Response.FAILURE_CODE , Response.FAILURE_MESSAGE);
            return response;
        }

        result.put("surUntreated" , surUntreated);
        result.put("patUploaded" , patUploaded);
        response.setResultCodeAndMessageAndResult(Response.SUCCESS_CODE , Response.SUCCESS_MESSAGE , JsonUtils.toJsonString(result));

        return response;
    }


    /**
     * 添加押金单/问诊单 yyt.bone.order.deposit.add
     * 
     *
     * @param data
     * @return
     */
    public Response addOrderDeposit(String data) {
        logger.info("添加押金单/问诊单, 方法入参data=" + data);
        Response response = new Response();
        OrderExtVo vo = JsonUtils.parseObject(data, OrderExtVo.class);
        OrderBoneExtendVo obeVo = JsonUtils.parseObject(data, OrderBoneExtendVo.class);

        if(StringUtils.isBlank(vo.getPlatformOrgAppCode())){
            logger.info("订单生成失败，入参PLATFORM_ORG_APP_CODE为空值.");
            response.setResultCodeAndMessage(Response.FAILURE_CODE , "订单生成失败，入参PLATFORM_ORG_APP_CODE为空值");
            return response;
        }

        OrderExtVo order = new OrderExtVo();
        OrderBoneExtendVo orderExtend = new OrderBoneExtendVo();

        //获得platform
        OrgApp orgApp = null;
        Map<String, String> map = new HashMap<>();
        map.put("org_app_code",vo.getPlatformOrgAppCode());
        response = BaseService.callHumpFromInternal("yyt.base.orgapp.get" , JsonUtils.toJsonString(map));
        if("0".equals(response.getResultCode())){
            orgApp = JsonUtils.parseObject(response.getResult(), OrgApp.class);
        }else{
            response.setResultCodeAndMessage(Response.FAILURE_CODE , "ORG_APP_CODE error!");
            return response;
        }

        order.setId(PKGenerator.generateId());
        order.setPlatformId(orgApp.getOrgId());
        order.setPlatformName(orgApp.getOrgName());
        order.setPlatformCode(orgApp.getOrgCode());
        order.setPlatformOrgAppName(orgApp.getOrgAppName());
        order.setPlatformOrgAppCode(vo.getPlatformOrgAppCode());

        String orderNo = CacheService.generateOrderNum(9, 6);
        order.setOrderNo(orderNo);
        order.setOpenId(vo.getOpenId());
        order.setOrgCode(ORG_CODE);
        order.setOrgId(ORG_ID);
        order.setOrgName(ORG_NAME);
        if(vo.getPayMode()==Short.valueOf("3")||vo.getPayMode()== Short.valueOf("4")){//线下生产订单
            order.setOrderStatus((short) 91);
            order.setPayStatusPayed();
            order.setPayMode(vo.getPayMode());
            order.setPaymentDealId(vo.getPaymentDealId());
            order.setPayTime(DateUtils.dateToString(new Date()));
            order.setUpdateTime(DateUtils.dateToString(new Date()));
        }else {
            // 90：待缴问诊费
            order.setOrderStatus((short) 90);
            order.setPayStatusNotPay();
            order.setPayMode((short) 0);
        }

        // 91为问诊单、92为手术单、93为押金单
        order.setOrderType(vo.getOrderType());
        order.setUserName(vo.getUserName());
        order.setUserAddress(vo.getUserAddress());
        order.setPayUserId(vo.getUserId());
        order.setUserId(vo.getUserId());
        order.setIdCardNo(vo.getIdCardNo());
        order.setIdCardType((short) 1);
        order.setUserMobile(vo.getUserMobile());
        order.setUserSex(vo.getUserSex());
        order.setCreatedTime(DateUtils.dateToString(new Date()));
        order.setIsInsurance((short) 0);
        order.setPayAmount(vo.getPayAmount());
        order.setPayRealAmount(vo.getPayAmount());
        order.setTotalAmount(vo.getPayAmount());
        order.setAccountAmount(0);
        order.setMedicareAmount(0);
        order.setInsuranceAmount(0);

        Map<String, String> extraParamsMap = new HashMap<String, String>();
        extraParamsMap.put("user_age", vo.getUserAge());
        if (obeVo.getProfessorDoctorRecvAmount()!=null&&
                org.apache.commons.lang.StringUtils.isNotBlank(String.valueOf(obeVo.getProfessorDoctorRecvAmount()))) {
        	// 主治顾问费
        	extraParamsMap.put("professor_doctor_recv_amount", obeVo.getProfessorDoctorRecvAmount().toString());
        }
        if(org.apache.commons.lang.StringUtils.isNotBlank(obeVo.getExpectedAurgeryTime())){
            //期望手术时间
            extraParamsMap.put("expected_aurgery_time", obeVo.getExpectedAurgeryTime().toString());
        }
        order.setExtraParams(JsonUtils.toJsonString(extraParamsMap));

        BeanUtils.copyProperties(obeVo, orderExtend);
        orderExtend.setOrderNo(orderNo);
        orderExtend.setId(PKGenerator.generateId());
        short orderType = vo.getOrderType();
        if (orderType == 93) {
        	// 押金单收入写死
        	String professorDoctorId = orderExtend.getProfessorDoctorId();
        	if (StringUtils.isBlank(professorDoctorId)) {
        		// 无主治，专家100，平台100
        		orderExtend.setAppointmentDoctorRecvAmount(100_00);
        		orderExtend.setPlatformServiceFee(100_00);
        	} else {
        		orderExtend.setProfessorDoctorRecvAmount(80_00);;
        		orderExtend.setAppointmentDoctorRecvAmount(100_00);
        		orderExtend.setPlatformServiceFee(20_00);
        	}
        }

        logger.info("添加押金单/问诊单, 调用base模块, 添加订单入参request=" + JsonUtils.toJsonString(order));
        Response baseRespone = BaseService.callUnderlineFromInternal("yyt.base.order.add",
                JsonUtils.toJsonString(order));
        logger.info("添加押金单/问诊单, 调用base模块, 添加订单返回response=" + JsonUtils.toJsonString(baseRespone));
        if (!baseRespone.getResultCode().equals("0")) {
            response.setResultCodeAndMessage("1001", "生成订单失败");
            return response;
        }
        if(vo.getPayMode()==Short.valueOf("3")||vo.getPayMode()== Short.valueOf("4")){
            logger.info("添加押金单（构造线下流水）开始");
            insertPaymentJournal(buildJournal(order));
            logger.info("添加押金单（构造线下流水）结束");
        }
        logger.info("添加押金单/问诊单, 调用order模块, 添加骨科订单拓展信息入参request=" + JsonUtils.toJsonString(orderExtend));
        Response orderRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.extend.add",
                JsonUtils.toJsonString(orderExtend));
        logger.info("添加押金单/问诊单, 调用order模块, 添加骨科订单拓展信息返回response=" + JsonUtils.toJsonString(orderRespone));
        if (!orderRespone.getResultCode().equals("0")) {
            response.setResultCodeAndMessage("1001", "生成订单拓展失败");
            return response;
        }

        response.setResultCodeAndMessage("0", "生成订单成功");
        response.setResult(JsonUtils.toJsonString(order));
        return response;
    }

    /**
     * 添加面诊单 yyt.bone.order.diagnose.add
     * @param data
     * @return
     */
    public Response addOrderDiagnose(String data){
        logger.info("添加面诊单, 方法入参data=" + data);
        Response response = new Response();
        try {
            OrderExtVo vo = JsonUtils.parseObject(data, OrderExtVo.class);
            OrderBoneExtendVo obeVo = JsonUtils.parseObject(data, OrderBoneExtendVo.class);
            //添加订单写入信息
            vo.setId(PKGenerator.generateId());
            vo.setCreatedTime(DateUtils.dateToString(new Date()));
            vo.setUpdateTime(DateUtils.dateToString(new Date()));

            //获得platform
            OrgApp orgApp = null;
            Map<String, String> map = new HashMap<>();
            map.put("org_app_code",vo.getPlatformOrgAppCode());
            response = BaseService.callHumpFromInternal("yyt.base.orgapp.get" , JsonUtils.toJsonString(map));
            if("0".equals(response.getResultCode())){
                orgApp = JsonUtils.parseObject(response.getResult(), OrgApp.class);
            }else{
                response.setResultCodeAndMessage(Response.FAILURE_CODE , "ORG_APP_CODE error!");
                return response;
            }
            vo.setPlatformId(orgApp.getOrgId());
            vo.setPlatformName(orgApp.getOrgName());
            vo.setPlatformCode(orgApp.getOrgCode());
            vo.setPlatformOrgAppName(orgApp.getOrgAppName());
            vo.setPlatformOrgAppCode(vo.getPlatformOrgAppCode());
            vo.setOrgCode(ORG_CODE);
            vo.setOrgId(ORG_ID);
            vo.setOrgName(ORG_NAME);

            String orderNo = CacheService.generateOrderNum(9, 6);
            vo.setOrderNo(orderNo);
            //订单初始状态为 100：待缴面诊费
            vo.setOrderStatus((short) 100);
            //面诊订单类型为94
            vo.setOrderType((short)94);
            vo.setPayStatusNotPay();
            //获取预约号
            vo.setReserveNo(generateReserveNo(null,4));

            obeVo.setOrderNo(orderNo);
            obeVo.setId(PKGenerator.generateId());

            Map<String, String> extraParamsMap = new HashMap<String, String>();
            extraParamsMap.put("user_age", vo.getUserAge());
            if (obeVo.getProfessorDoctorRecvAmount() != null) {
                // 主治顾问费
                extraParamsMap.put("appointment_doctor_recv_amount", obeVo.getProfessorDoctorRecvAmount().toString());
            }
            vo.setExtraParams(JsonUtils.toJsonString(extraParamsMap));

            //查询号源信息
            BoneDiagnose boneDiagnose = new BoneDiagnose();
            boneDiagnose.setDoctorId(obeVo.getProfessorDoctorId());
            boneDiagnose.setDeptId(vo.getDeptId());
            boneDiagnose.setConsultationTime(vo.getScheduleTime());
            List<BoneDiagnose> list = boneDiagnoseDao.select(boneDiagnose);
            if(list.isEmpty()){
                response.setResultCodeAndMessage("-3","号源不存在!");
                return response;
            }
            if(list.get(0).getSubscribeNum()>=2){
                response.setResultCodeAndMessage("-4","号源已预约完!");
                return response;
            }
            vo.setTotalAmount(list.get(0).getConsultationFee());
            vo.setUserAddress(list.get(0).getAddress());
            logger.info("添加押面诊订单, 调用base模块, 添加订单入参request=" + JsonUtils.toJsonString(vo));
            Response baseRespone = BaseService.callUnderlineFromInternal("yyt.base.order.add",
                    JsonUtils.toJsonString(vo));
            logger.info("添加面诊订单, 调用base模块, 添加订单返回response=" + JsonUtils.toJsonString(baseRespone));
            if (!baseRespone.getResultCode().equals("0")) {
                response.setResultCodeAndMessage("1001", "生成订单失败!");
                return response;
            }

            logger.info("添加面诊订单, 调用order模块, 添加骨科订单拓展信息入参request=" + JsonUtils.toJsonString(obeVo));
            Response orderRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.extend.add",
                    JsonUtils.toJsonString(obeVo));
            logger.info("添加面诊订单, 调用order模块, 添加骨科订单拓展信息返回response=" + JsonUtils.toJsonString(orderRespone));
            if (!orderRespone.getResultCode().equals("0")) {
                response.setResultCodeAndMessage("1001", "生成订单失败！");
                return response;
            }

            logger.info("生成面诊订单，更新号源");
            list.get(0).setSubscribeNum(list.get(0).getSubscribeNum()+1);
            boneDiagnoseDao.update(list.get(0));
            logger.info("更新号源成功，入参："+list.get(0).toString());

            response.setResultCodeAndMessage("0", "生成订单成功!");
            response.setResult(JsonUtils.toJsonString(vo));
        }catch (Exception e){
            logger.info("添加面诊订单异常",e);
            response.setResultCodeAndMessage("-1","生成订单异常！");
        }
        return  response;
    }

    private String generateReserveNo(String digits, int length) {
        String code = cn.yunyichina.utils.commons.StringUtils.getRandom(digits,length);
        String returnCode="";
        OrderExtVo vo = new OrderExtVo();
        vo.setReserveNo(code);
        vo.setOrderType((short) 94);
        //订单状态为101 :已缴面诊费用
        vo.setOrderStatus((short)101);
        Response baseRespone = BaseService.callUnderlineFromInternal("yyt.base.order.list.get",
                JsonUtils.toJsonString(vo));
        JSONArray jsonArray = JsonUtils.parseArray(baseRespone.getResult());
        if(jsonArray.size()==0){
           returnCode=code;
        }else{
            return generateReserveNo(digits,length);
        }
        return returnCode;
    }

    /**
     * 更新面诊单 yyt.bone.order.diagnose.update
     * @param data
     * @return
     */
    public Response updateOrderDiagnose(String data){
        Response response = new Response();
        try{
            OrderExtVo vo = JsonUtils.parseObject(data, OrderExtVo.class);
            OrderBoneExtendVo voExtend = JsonUtils.parseObject(data, OrderBoneExtendVo.class);
            Map<String,Object> jsonMap = new HashMap<>();
            jsonMap.put("order_no",vo.getOrderNo());
            final String orderNo =vo.getOrderNo();
            logger.info("获取订单信息, 调用order模块, 入参request=" + JsonUtils.toJsonString(jsonMap));
            Response order = OrderService.callUnderlineFromInternal("yyt.order.bone.order.get",
                    JsonUtils.toJsonString(vo));
            logger.info("获取订单信息, 调用order模块, 返回respone=" + JsonUtils.toJsonString(order));
            if (!order.getResultCode().equals("0")) {
                return Response.failure();
            }
            OrderExtVo orderVo = JsonUtils.parseObject(order.getResult(),OrderExtVo.class);
            OrderBoneExtendVo obeVo = JsonUtils.parseObject(order.getResult(), OrderBoneExtendVo.class);
            if(vo.getReserveNo()!=null){
                if(!vo.getReserveNo().equals(orderVo.getReserveNo())){
                    response.setResultCodeAndMessage("-3","预约号有误!");
                    return  response;
                }
            }
            //金额设置
            JSONObject jsonObject = new JSONObject();
            String userId =obeVo.getAppointmentDoctorId();
            jsonObject.put("user_id",userId);
            logger.info("添加面诊订单, 调用base模块, 查询医生信息" + JsonUtils.toJsonString(jsonObject));
            Response res = BaseService.callUnderlineFromInternal("yyt.base.orguser.info.get",
                    JsonUtils.toJsonString(jsonObject));
            JSONObject orgUserVo = JsonUtils.parseObject(res.getResult(),JSONObject.class);
            String extraParams = orgUserVo.get("extraParams").toString().replaceAll("\\\\","");
            JSONObject obj = JSON.parseObject(extraParams);
            if(obj != null){
                Double divide = Double.valueOf(obj.get("DOCTOR_DIVIDE")==null?"1":obj.get("DOCTOR_DIVIDE").toString());
                obeVo.setAppointmentDoctorRecvAmount((int) (orderVo.getTotalAmount()*divide));
                obeVo.setPlatformServiceFee((int) (orderVo.getTotalAmount()*(1-divide)));
            }
            obeVo.setManageStatus(Short.valueOf("1"));//修改订单状态为已处理
            vo.setUpdateTime(DateUtils.getDateTimeStr());
            logger.info("更新押面诊订单, 调用base模块, 更新订单入参request=" + JsonUtils.toJsonString(vo));
            Response baseRespone = BaseService.callUnderlineFromInternal("yyt.base.order.update",
                    JsonUtils.toJsonString(vo));
            logger.info("更细n面诊订单, 调用base模块, 更新订单返回response=" + JsonUtils.toJsonString(baseRespone));
            if (!baseRespone.getResultCode().equals("0")) {
                response.setResultCodeAndMessage("1001", "更新订单失败");
                return response;
            }
            logger.info("更新面诊订单, 调用order模块, 更新骨科订单拓展信息入参request=" + JsonUtils.toJsonString(obeVo));
            Response orderRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.extend.update",
                    JsonUtils.toJsonString(obeVo));
            logger.info("更新面诊订单, 调用order模块,更新骨科订单拓展信息返回response=" + JsonUtils.toJsonString(orderRespone));
            if (!orderRespone.getResultCode().equals("0")) {
                response.setResultCodeAndMessage("1001", "更新订单拓展失败");
                return response;
            }


        }catch (Exception e){
            logger.error("更新面诊订单异常",e);
            response.setResultCodeAndMessage("-1","更新面诊订单异常!");
        }

        return response;
    }
    /**
     * 添加手术单 yyt.bone.order.operation.add
     *
     * @param data
     * {
     *     "order_no": "关联的押金单订单号"
     *     "pay_amount": "手术定价",
     *     "diagnosis_reply": "会诊意见",
     *     "can_surgery_time": "2017-05-08 12:00:00",
     *     "surgery_time": "2017-05-08 12:00:00"
     * }
	 *
     * @return
     */
    public Response addOrderOperation(String data) {
        logger.info("添加手术单, 方法入参data=" + data);
        Response response = new Response();
        OrderExtVo orderVo = JsonUtils.parseObject(data, OrderExtVo.class);
        OrderBoneExtendVo orderExtendVo = JsonUtils.parseObject(data, OrderBoneExtendVo.class);

        OrderExtVo depositOrder = new OrderExtVo();
        OrderExtVo operationOrder = new OrderExtVo();
        OrderBoneExtendVo depositOrderExtend = new OrderBoneExtendVo();
        OrderBoneExtendVo operationOrderExtend = new OrderBoneExtendVo();

        // orderNo 手术单对应的押金单号
        if (StringUtils.isNotBlank(orderVo.getOrderNo())) {
            logger.info("添加手术单, 调用order模块, 获取押金单信息入参request=" + JsonUtils.toJsonString(orderVo));
            Response orderRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.order.get",
                    JsonUtils.toJsonString(orderVo));
            logger.info("添加手术单, 调用order模块, 获取押金单信息返回response=" + JsonUtils.toJsonString(orderRespone));
            if (!orderRespone.getResultCode().equals("0")) {
                return Response.failure();
            }

            // 取出押金单信息
            OrderExtVo orderTmp = JsonUtils.parseObject(orderRespone.getResult(), OrderExtVo.class);
            BeanUtils.copyProperties(orderTmp, operationOrder);
            
            // 取出押金单拓展信息
            OrderBoneExtendVo orderExtendTmp = JsonUtils.parseObject(orderRespone.getResult(), OrderBoneExtendVo.class);
            BeanUtils.copyProperties(orderExtendTmp, operationOrderExtend);
            
            if(StringUtils.isNotBlank(orderExtendTmp.getDiagnosisOrderNo())) {
                return Response.failure("已存在手术单，不能重复生成。");
            }

            //检查该押金单号是否已存在对应手术单
            OrderExtVo extVo = new OrderExtVo();
            extVo.setOrderNo(orderVo.getOrderNo());
            Response depReps = getOrderOperationByDepositOrderNo(JsonUtils.toJsonString(extVo));
            if("0".equals(depReps.getResultCode())){
                if(depReps.getResult() != null){
                    logger.info("添加手术单失败，已存在该押金单对应手术单信息 json-->" + JsonUtils.toJsonString(depReps.getResult()));
                    return Response.failure("添加手术单失败，已存在该押金单对应手术单信息 json-->" + JsonUtils.toJsonString(depReps.getResult()));
                }
            }

            Map<String, String> resultMap = JsonUtils.parseObject(orderRespone.getResult(), Map.class);
            // 设置押金单id, 用于后面更新订单信息逻辑
            depositOrder.setId(resultMap.get("id"));
            // 设置押金单拓展信息id, 用于后面更新订单信息逻辑
            depositOrderExtend.setId(resultMap.get("bone_extend_id"));
        }
        
        // 设置押金单业务状态为: "专家已反馈"
        depositOrder.setOrderStatus((short) 94);

        // 生成一个新的手术单
        // 设置手术单业务状态为: "专家已反馈"

        if(orderVo.getPayMode()==Short.valueOf("3")||orderVo.getPayMode()== Short.valueOf("4")){//线下生产订单
            operationOrder.setOrderStatus((short) 97);
            operationOrder.setPayStatusPayed();
            operationOrder.setPayMode(orderVo.getPayMode());
            operationOrder.setPaymentDealId(orderVo.getPaymentDealId());
            operationOrder.setPayTime(DateUtils.dateToString(new Date()));
            operationOrder.setUpdateTime(DateUtils.dateToString(new Date()));
        }else {
            operationOrder.setOrderStatus((short) 94);
            operationOrder.setPayStatusNotPay();
            operationOrder.setPayTime(null);
            operationOrder.setPaymentDealId(null);
        }
        operationOrder.setOrderType((short) 92);
        operationOrder.setId(PKGenerator.generateId());
        String orderNo = CacheService.generateOrderNum(9, 6);
        operationOrder.setOrderNo(orderNo);
        // 这个金额其实是手术报价，后面更新订单会传一些相应的金额
        operationOrder.setPayAmount(orderVo.getPayAmount());
        operationOrder.setPayRealAmount(orderVo.getPayAmount());
        operationOrder.setTotalAmount(orderVo.getPayAmount());


        // 修改押金单拓展信息的手术时间等信息
        // 设置押金单关联的手术单订单号
        depositOrderExtend.setDiagnosisOrderNo(orderNo);
        depositOrderExtend.setDiagnosisReply(orderExtendVo.getDiagnosisReply());
        depositOrderExtend.setCanSurgeryTime(orderExtendVo.getCanSurgeryTime());
        depositOrderExtend.setSurgeryTime(orderExtendVo.getSurgeryTime());
        depositOrderExtend.setIsAcceptSurgery((short) 1);

        // 生成一个新的手术单扩展订单信息
        operationOrderExtend.setOrderNo(orderNo);
        operationOrderExtend.setId(PKGenerator.generateId());
        // 设置手术单关联的问诊单订单号
        operationOrderExtend.setDiagnosisOrderNo(orderVo.getOrderNo());
        operationOrderExtend.setDiagnosisReply(orderExtendVo.getDiagnosisReply());
        operationOrderExtend.setCanSurgeryTime(orderExtendVo.getCanSurgeryTime());
        operationOrderExtend.setSurgeryTime(orderExtendVo.getSurgeryTime());
        operationOrderExtend.setIsAcceptSurgery((short) 1);
        // 设置手术单的相关费用
        operationOrderExtend.setProfessorDoctorRecvAmount(orderExtendVo.getProfessorDoctorRecvAmount());
        operationOrderExtend.setAppointmentDoctorRecvAmount(orderExtendVo.getAppointmentDoctorRecvAmount());

        if(orderVo.getPayMode()==Short.valueOf("3")||orderVo.getPayMode()== Short.valueOf("4")) {//线下生产订单
            operationOrderExtend.setAppointmentDoctorRecvAmount(orderExtendVo.getAppointmentDoctorRecvAmount());
            operationOrderExtend.setProfessorDoctorRecvAmount(orderExtendVo.getProfessorDoctorRecvAmount());
            operationOrderExtend.setPlatformServiceFee(orderExtendVo.getPlatformServiceFee());
            updateSurgeryOrderFeeAndTotal(operationOrder, operationOrderExtend);
        }else {
            updateSurgeryOrderFee(operationOrder, operationOrderExtend);
        }
        // 更新押金单业务状态为"专家已反馈"
        logger.info("添加手术单, 调用base模块, 更新押金单入参request=" + JsonUtils.toJsonString(depositOrder));
        BaseService.callUnderlineFromInternal("yyt.base.order.update", JsonUtils.toJsonString(depositOrder));

        // 新生成的手术单入库order
        logger.info("添加手术单, 调用base模块, 添加手术单入参request=" + JsonUtils.toJsonString(operationOrder));
        Response baseRespone = BaseService.callUnderlineFromInternal("yyt.base.order.add",
                JsonUtils.toJsonString(operationOrder));
        logger.info("添加手术单, 调用base模块, 添加手术单返回response=" + JsonUtils.toJsonString(baseRespone));
        if (!baseRespone.getResultCode().equals("0")) {
            response.setResultCodeAndMessage("1001", "生成订单失败");
            return response;
        }
        if(orderVo.getPayMode()==Short.valueOf("3")||orderVo.getPayMode()== Short.valueOf("4")){
            logger.info("添加手术单（构造线下流水）开始");
            insertPaymentJournal(buildJournal(operationOrder));
            logger.info("添加手术单（构造线下流水）结束");
        }
        // 更新押金单的拓展信息ord_order_bone_extend
        logger.info("添加手术单, 调用order模块, 修改押金单拓展信息入参request=" + JsonUtils.toJsonString(depositOrderExtend));
        Response orderRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.extend.by.id.update",
                JsonUtils.toJsonString(depositOrderExtend));
        logger.info("添加手术单, 调用order模块, 修改押金单拓展信息返回response=" + JsonUtils.toJsonString(orderRespone));
        if (!orderRespone.getResultCode().equals("0")) {
            response.setResultCodeAndMessage("1001", "更新订单拓展失败");
            return response;
        }

        // 新生成的手术单拓展信息单入库ord_order_bone_extend
        logger.info("添加手术单, 调用order模块, 添加手术单拓展信息入参request=" + JsonUtils.toJsonString(operationOrderExtend));
        Response orderExtRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.extend.add",
                JsonUtils.toJsonString(operationOrderExtend));
        logger.info("添加手术单, 调用order模块, 添加手术单拓展信息返回response=" + JsonUtils.toJsonString(orderExtRespone));
        if (!orderRespone.getResultCode().equals("0")) {
            response.setResultCodeAndMessage("1001", "生成订单拓展失败");
            return response;
        }

        response.setResultCodeAndMessage("0", "生成订单成功");
        response.setResult(JsonUtils.toJsonString(operationOrder));
        return response;
    }

    /**
     * 获取订单信息 yyt.bone.order.get
     *
     * @param data
     * @return
     */
    public Response getOrder(String data) {
        logger.info("获取订单信息, 入参data=" + data);
        Response response = new Response();
        OrderExtVo vo = JsonUtils.parseObject(data, OrderExtVo.class);

        logger.info("获取订单信息, 调用order模块, 入参request=" + JsonUtils.toJsonString(vo));
        Response orderRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.order.get",
                JsonUtils.toJsonString(vo));
        logger.info("获取订单信息, 调用order模块, 返回respone=" + JsonUtils.toJsonString(orderRespone));
        if (!orderRespone.getResultCode().equals("0")) {
            return Response.failure();
        }

        response.setResult(JsonUtils.toJsonString(orderRespone.getResult()));

        return response;
    }

    /**
     * 根据押金单订单号获取手术单信息 yyt.bone.order.operation.by.deposit.order.no.get
     *
     * @param data
     * @return
     */
    public Response getOrderOperationByDepositOrderNo(String data) {
        logger.info("根据押金单订单号获取手术单信息, 入参data: " + data);
        Response response = new Response();
        OrderExtVo vo = JsonUtils.parseObject(data, OrderExtVo.class);

        logger.info("根据押金单订单号获取手术单信息, 调用order模块, 入参request=" + JsonUtils.toJsonString(vo));
        Response orderRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.order.operation.by.deposit.order.no.get",
                JsonUtils.toJsonString(vo));
        logger.info("根据押金单订单号获取手术单信息, 调用order模块, 返回response=" + JsonUtils.toJsonString(orderRespone));
        if (!orderRespone.getResultCode().equals("0")) {
            return Response.failure();
        }

        response.setResult(JsonUtils.toJsonString(orderRespone.getResult()));

        return response;
    }

    /**
     * 根据问诊单订单号修改手术单信息 yyt.bone.order.operation.update
     * 更新问诊单，押金单，手术单
     *
     * @param data
     * @return
     */
    public Response updateOrderOperation(String data) {
        logger.info("updateOrderOperation data: " + data);
        Response response = new Response();
        // 订单信息 order
        OrderExtVo vo = JsonUtils.parseObject(data, OrderExtVo.class);
        OrderBoneExtendVo orderBoneExtendVo = JsonUtils.parseObject(data, OrderBoneExtendVo.class); // 订单拓展信息 orderExtend
        vo.setUpdateTime(DateUtils.dateToString(new Date()));
        Map<String,String> map = JsonUtils.parseObject(data,Map.class);
        String type = map.get("method_type");   //方法类型： 1.修改订单详情  2.确认订单完成

        Boolean feeFlag = false;
        int platformServiceFeeEx = 0;
        if(orderBoneExtendVo.getPlatformServiceFee() != null){
            platformServiceFeeEx = orderBoneExtendVo.getPlatformServiceFee();
            feeFlag = true;
        }
        
        // 手术订单需要更新平台服务费等
        short orderType = vo.getOrderType();
        if (92 == orderType) {
            Response orderResponse = OrderService.callUnderlineFromInternal("yyt.order.bone.order.get",
                    JsonUtils.toJsonString(vo));
            logger.info("查询订单详细信息，入参: " + JsonUtils.toJsonString(vo) + "，出参: " + JsonUtils.toJsonString(orderResponse));
            if (!"0".equals(orderResponse.getResultCode()) || StringUtils.isBlank(orderResponse.getResult())) {
                logger.error("查询订单详细信息失败 " + JsonUtils.toJsonString(orderResponse));
                return Response.failure();
            }

            // 获取更新之前的主治和专家费用
            OrderBoneExtendVo oldBoneExtendVo = JsonUtils.parseObject(orderResponse.getResult(), OrderBoneExtendVo.class);
            Integer oldProfessorDoctorRecvAmount = oldBoneExtendVo.getProfessorDoctorRecvAmount();
            Integer oldAppointmentDoctorRecvAmount = oldBoneExtendVo.getAppointmentDoctorRecvAmount();

            // 如果入参里面有新的主治或者专家费用，就要更新
            Integer newProfessorDoctorRecvAmount = orderBoneExtendVo.getProfessorDoctorRecvAmount();
            Integer newAppointmentDoctorRecvAmount = orderBoneExtendVo.getAppointmentDoctorRecvAmount();
            if (newProfessorDoctorRecvAmount != null || newAppointmentDoctorRecvAmount != null) {
        		// 如果哪个费用没有传，表示不更新，取原来的值
        		if (newProfessorDoctorRecvAmount == null) {
        			orderBoneExtendVo.setProfessorDoctorRecvAmount(oldProfessorDoctorRecvAmount);
        		}
        		if (newAppointmentDoctorRecvAmount == null) {
        			orderBoneExtendVo.setAppointmentDoctorRecvAmount(oldAppointmentDoctorRecvAmount);
        		}

        		if(StringUtils.isNotBlank(type) && "1".equals(type)){
                    updateSurgeryOrderFeeAndTotal(vo, orderBoneExtendVo);   // 修改订单详情时统计算法
                }else{
                    updateSurgeryOrderFee(vo, orderBoneExtendVo);
                }
        	}

            //更新传入平台服务费
            if(feeFlag){
                orderBoneExtendVo.setPlatformServiceFee(platformServiceFeeEx);
            }
        }


        Response orderRespone = BaseService.callUnderlineFromInternal("yyt.base.order.update",
                JsonUtils.toJsonString(vo));

        logger.info("updateOrderOperation, orderRespone=" + JsonUtils.toJsonString(orderRespone));
        if (!orderRespone.getResultCode().equals("0")) {
            return Response.failure();
        }

        Response orderBoneExtendRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.extend.by.order.no.update",
        		JsonUtils.toJsonString(orderBoneExtendVo));
        logger.info("updateOrderOperation, orderBoneExtendRespone=" + JsonUtils.toJsonString(orderBoneExtendRespone));
        if (!orderBoneExtendRespone.getResultCode().equals("0")) {
            return Response.failure();
        }
        logger.info("updateOrderOperation, success");
        response.setResult(JsonUtils.toJsonString(orderRespone.getResult()));

        return response;
    }
    
    /**
     * 确认订单时生成流水 yyt.bone.order.account.journal.generate
     * 
     * @param data order_no
     * @return
     */
    public Response generateOrderAccountJournal(String data) {
    	logger.info("[yyt.bone.order.account.journal.generate]确认订单时生成流水，入参 data: " + data);
    	JSONObject object = JSON.parseObject(data);
    	final String orderNo = object.getString("order_no");
    	if (StringUtils.isBlank(orderNo)) {
    		logger.error("[yyt.bone.order.account.journal.generate]确认订单时生成流水失败，缺少入参: order_no");
    		return Response.failure("确认订单时生成流水失败，缺少入参: order_no");
    	}
    	
    	// 生成流水可能很慢，需要异步执行
    	new Thread(new Runnable() {
			
			@Override
			public void run() {
				ResCommon<Void> result = FinanceService.getFinanceClient().saveAccountJournal(orderNo);
				logger.info("[yyt.bone.order.account.journal.generate]确认订单时生成流水，{orderNo: "
						+ orderNo
						+ ", resultCode: "
						+ result.getResultCode()
						+ ", resultMessage: " + result.getResultMessage() + "}");
			}
		}).start();
    	
    	return new Response();
    }
    
	/**
	 * 计算手术单平台服务费，意外险
	 * 
	 * @param orderVo
	 * @param orderBoneVo
	 */
	private void updateSurgeryOrderFee(OrderExtVo orderVo, OrderBoneExtendVo orderBoneVo) {
		int professorDoctorRecvAmount = (orderBoneVo
				.getProfessorDoctorRecvAmount() == null ? 0 : orderBoneVo
				.getProfessorDoctorRecvAmount());
		int appointmentDoctorRecvAmount = (orderBoneVo
				.getAppointmentDoctorRecvAmount() == null ? 0 : orderBoneVo
				.getAppointmentDoctorRecvAmount());
		int platformServiceFee = Long
				.valueOf(
						Math.round((professorDoctorRecvAmount + appointmentDoctorRecvAmount)
								* PLATFORM_SERVICE_RATE)).intValue();
		int surgeryAccidentFee = SURGERY_ACCIDENT_FEE;   //取消手术意外险
		int discountAmount = DISCOUNT_AMOUNT;

		// 总金额 = 主治收入 + 专家收入 + 平台服务费 + 折扣的金额
		int totalAmount = professorDoctorRecvAmount
				+ appointmentDoctorRecvAmount + platformServiceFee
                + discountAmount;

		orderVo.setPayAmount(totalAmount);
		orderVo.setTotalAmount(totalAmount);
		orderVo.setPayRealAmount(totalAmount);

//		orderBoneVo.setSurgeryAccidentFee(surgeryAccidentFee);
        orderBoneVo.setDiscountAmount(discountAmount);
        orderBoneVo.setPlatformServiceFee(platformServiceFee);
    }




    /**
     * 计算手术单平台服务费、总金额v2.0
     *
     * @param orderVo
     * @param orderBoneVo
     */
    private void updateSurgeryOrderFeeAndTotal(OrderExtVo orderVo, OrderBoneExtendVo orderBoneVo) {
        int professorDoctorRecvAmount = (orderBoneVo
                .getProfessorDoctorRecvAmount() == null ? 0 : orderBoneVo
                .getProfessorDoctorRecvAmount());
        int appointmentDoctorRecvAmount = (orderBoneVo
                .getAppointmentDoctorRecvAmount() == null ? 0 : orderBoneVo
                .getAppointmentDoctorRecvAmount());
        int platformServiceFee = orderBoneVo.getPlatformServiceFee() == null ? 0 : orderBoneVo.getPlatformServiceFee();
        int discountAmount = DISCOUNT_AMOUNT;

        // 支付金额 = 专家定价 + 顾问费 + 平台服务费 + 折扣金额（-200）
        int totalAmount = appointmentDoctorRecvAmount + professorDoctorRecvAmount + platformServiceFee + discountAmount;

        orderVo.setPayAmount(totalAmount);
        orderVo.setTotalAmount(totalAmount);
        orderVo.setPayRealAmount(totalAmount);

        orderBoneVo.setDiscountAmount(discountAmount);
        orderBoneVo.setPlatformServiceFee(platformServiceFee);
    }

    /**
     * 创建线下支付对应云医支付流水对象
     *
     */
    private PaymentJournalVo buildJournal(OrderExtVo orderExtVo) {
        PaymentJournalVo journal = new PaymentJournalVo();
        journal.setId(UUIDUtil.get32UUID());
        journal.setPaymentDealNo(NumberUtil.buildPaymentDealNo());
        journal.setOrgId(orderExtVo.getOrgId());
        journal.setOrgCode(orderExtVo.getOrgCode());
        journal.setOrgName(orderExtVo.getOrgName());
        journal.setPlatformId(orderExtVo.getPlatformId());
        journal.setPlatformName(orderExtVo.getPlatformName());
        journal.setPlatformOrgAppCode(orderExtVo.getPlatformOrgAppCode());
        journal.setPlatformOrgAppName(orderExtVo.getPlatformOrgAppName());
        journal.setBranchId(orderExtVo.getBranchId());
        journal.setBranchCode(orderExtVo.getBranchCode());
        journal.setBranchName(orderExtVo.getBranchName());
        journal.setOutOrderNo(orderExtVo.getOutOrderNo());
        journal.setOrderType(orderExtVo.getOrderType());
        journal.setAccountAmount(orderExtVo.getAccountAmount());
        journal.setMedicareAmount(orderExtVo.getMedicareAmount());
        journal.setInsuranceAmount(orderExtVo.getInsuranceAmount() == null ? 0 : orderExtVo.getInsuranceAmount());
        journal.setPayAmount(orderExtVo.getPayAmount());
        journal.setTotalAmount(journal.getInsuranceAmount() + journal.getPayAmount());
        journal.setInsuranceMode(orderExtVo.getInsuranceMode());

        //journal.setPayAppId(params.get("appid"));
        journal.setOrderNo(orderExtVo.getOrderNo());
        journal.setHisOrderNo(orderExtVo.getHisOrderNo());
        journal.setPaymentDealId(orderExtVo.getPaymentDealId());
        journal.setPayStatus((short) 1);
        journal.setCheckStatus((short) 0);
        journal.setSettlementStatus((short) 0);
        if(orderExtVo.getPayMode()==Short.valueOf("3")){
            journal.setPayCode("UNIONPAY");
            journal.setPayMode((short)3);
        }else if(orderExtVo.getPayMode()==Short.valueOf("4")){
            journal.setPayCode("CASH");
            journal.setPayMode((short)4);
        }
        // journal.setDealAccount(params.get("openid"));
        journal.setPayTime(DateUtils.getDatetime());
        journal.setCreatedTime(DateUtils.getDatetime());
        logger.info("OrderServiceImpl.buildJournal.journal -> {}", JsonUtils.toJsonString(journal));
        return journal;
    }

    private void insertPaymentJournal(PaymentJournalVo paymentJournal) {
        PayService.getPayClient().addPaymentJournal(paymentJournal);
    }

    /**
     * 添加求助订单 (订单类型95)
     * yyt.bone.order.seek.help.add
     *
     * @param data
     * @return
     */
    public Response addOrderSeekHelp(String data){
        logger.info("添加名医求助订单addOrderSeekHelp,入参："+data);
        Response response = new Response();
        try {
            OrderExtVo vo = JsonUtils.parseObject(data, OrderExtVo.class);
            OrderBoneExtendVo obeVo = JsonUtils.parseObject(data, OrderBoneExtendVo.class);
            //添加订单写入信息
            vo.setId(PKGenerator.generateId());
            vo.setCreatedTime(DateUtils.dateToString(new Date()));
            vo.setUpdateTime(DateUtils.dateToString(new Date()));

            //获得platform
            OrgApp orgApp = null;
            Map<String, String> map = new HashMap<>();
            map.put("org_app_code",vo.getPlatformOrgAppCode());
            response = BaseService.callHumpFromInternal("yyt.base.orgapp.get" , JsonUtils.toJsonString(map));
            if("0".equals(response.getResultCode())){
                orgApp = JsonUtils.parseObject(response.getResult(), OrgApp.class);
            }else{
                response.setResultCodeAndMessage(Response.FAILURE_CODE , "ORG_APP_CODE error!");
                return response;
            }
            vo.setPlatformId(orgApp.getOrgId());
            vo.setPlatformName(orgApp.getOrgName());
            vo.setPlatformCode(orgApp.getOrgCode());
            vo.setPlatformOrgAppName(orgApp.getOrgAppName());
            vo.setPlatformOrgAppCode(orgApp.getOrgAppCode());
            vo.setOrgCode(ORG_CODE);
            vo.setOrgId(ORG_ID);
            vo.setOrgName(ORG_NAME);

            String orderNo = CacheService.generateOrderNum(9, 6);
            vo.setOrderNo(orderNo);
            //求助订单状态：待缴服务费：110、已缴服务费：111、已取消：112、已完成：113
            vo.setOrderStatus((short) 110);
            //求组订单类型95
            vo.setOrderType((short)95);
            vo.setPayStatusNotPay();

            obeVo.setOrderNo(orderNo);
            obeVo.setId(PKGenerator.generateId());

            Map<String, String> extraParamsMap = new HashMap<String, String>();
            extraParamsMap.put("user_age", vo.getUserAge());

            logger.debug("患者推送待缴费消息->获取发送用户信息addOrderSeekHelp->request:userId="+vo.getUserId());
            PersonalUserOpenid personalUserOpenid = BaseService.getBaseClient().getPersonalUserOpenidByAppCode(vo.getUserId(), vo.getPlatformOrgAppCode(),null);
            logger.debug("患者推送待缴费消息->获取发送用户信息addOrderSeekHelp->response:"+JsonUtils.toJsonString(personalUserOpenid));
            if (personalUserOpenid == null) {
                vo.setOpenId(null);
            }
            vo.setOpenId(personalUserOpenid.getOpenId());

            logger.info("添加求助订单, 调用base模块, 添加订单入参request=" + JsonUtils.toJsonString(vo));
            Response baseRespone = BaseService.callUnderlineFromInternal("yyt.base.order.add",
                    JsonUtils.toJsonString(vo));
            logger.info("添加求助订单, 调用base模块, 添加订单返回response=" + JsonUtils.toJsonString(baseRespone));
            if (!baseRespone.getResultCode().equals("0")) {
                response.setResultCodeAndMessage("1001", "生成求助订单失败!");
                return response;
            }

            logger.info("添加求助订单, 调用order模块, 添加骨科订单拓展信息入参request=" + JsonUtils.toJsonString(obeVo));
            Response orderRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.extend.add",
                    JsonUtils.toJsonString(obeVo));
            logger.info("添加求助订单, 调用order模块, 添加骨科订单拓展信息返回response=" + JsonUtils.toJsonString(orderRespone));
            if (!orderRespone.getResultCode().equals("0")) {
                response.setResultCodeAndMessage("1001", "生成求助订单失败！");
                return response;
            }
            response.setResultCodeAndMessage("0", "生成求助订单成功!");

            //生成订单成功  发送微信通知 发送短信通知
            sendMsgToUser(vo,obeVo);
        }catch (Exception e){
            logger.error("添加求助订单异常!"+e);
            response.setResultCodeAndMessage("-1","添加求助订单异常!");
        }
        return response;
    }

    /**
     * 更新求助订单 (订单类型95)
     * yyt.bone.order.seek.help.update
     *
     * @param data
     * @return
     */
    public Response updateOrderSeekHelp(String data) {
        logger.info("添加名医求助订单addOrderSeekHelp,入参：" + data);
        Response response = new Response();
        try {
            OrderExtVo vo = JsonUtils.parseObject(data, OrderExtVo.class);
            OrderBoneExtendVo obeVo = JsonUtils.parseObject(data, OrderBoneExtendVo.class);
            //求助订单状态：待缴服务费：110、已缴服务费：111、已取消：112、已完成：113
            vo.setOrderStatus((short) 113);
            vo.setUpdateTime(DateUtils.dateToString(new Date()));
            obeVo.setManageStatus(Short.valueOf("1"));//修改订单状态为已处理
            if(vo.getTotalAmount()-obeVo.getAppointmentDoctorRecvAmount()-obeVo.getProfessorDoctorRecvAmount()<0){
                response.setResultCodeAndMessage("-1","主治医生与专家收入不能超过订单总额!");
                return  response;
            }
            obeVo.setPlatformServiceFee(vo.getTotalAmount()-obeVo.getAppointmentDoctorRecvAmount()-obeVo.getProfessorDoctorRecvAmount());
            logger.info("更新求助订单, 调用base模块, 更新订单入参request=" + JsonUtils.toJsonString(vo));
            Response baseRespone = BaseService.callUnderlineFromInternal("yyt.base.order.update",
                    JsonUtils.toJsonString(vo));
            logger.info("更新求助订单, 调用base模块, 更新订单返回response=" + JsonUtils.toJsonString(baseRespone));
            if (!baseRespone.getResultCode().equals("0")) {
                response.setResultCodeAndMessage("1001", "更新订单失败");
                return response;
            }
            logger.info("更新求助订单, 调用order模块, 更新骨科订单拓展信息入参request=" + JsonUtils.toJsonString(obeVo));
            Response orderRespone = OrderService.callUnderlineFromInternal("yyt.order.bone.extend.update",
                    JsonUtils.toJsonString(obeVo));
            logger.info("更新求助订单, 调用order模块,更新骨科订单拓展信息返回response=" + JsonUtils.toJsonString(orderRespone));
            if (!orderRespone.getResultCode().equals("0")) {
                response.setResultCodeAndMessage("1001", "更新订单拓展失败");
                return response;
            }
        }catch (Exception e){
            logger.error("更新求助订单异常!"+e);
            response.setResultCodeAndMessage("-1","更新求助订单异常!");
        }
        return response;
    }
    private void sendMsgToUser(OrderExtVo vo, OrderBoneExtendVo obeVo) {
        //t推送微信 待缴费通知
        String firstMsg = "您好,"+vo.getUserName()+",您有一笔待缴费订单,请及时支付,24小时未支付,这笔订单将取消。";
        String templateCode = "50001";
        String remark ="如有相关疑问，可联系客服电话020-85600747。";
        String actionUrl = BoneMsgUtils.queryActionUrl("TMP50001")+vo.getOrderNo()+"&app_code="+vo.getPlatformOrgAppCode();
        String method = "yyt.message.msg.template.send";
        JSONObject jsonObject = JsonUtils.parseObject(vo.getExtraParams(),JSONObject.class);

        String messageContent = "{\"user_type\":\"2\",\"platform_type\":\"" + 1+ "\",\"org_app_code\":\"" + vo.getPlatformOrgAppCode() +  "\",\"org_code\":\"" + vo.getOrgCode() + "\",\"to_user\":\""
                + vo.getOpenId()
                + "\",\"template_code\":\"" + templateCode
                + "\",\"url\":\"" + actionUrl +
                "\",\"msg_content\":\"{\\\"first\\\": \\\"" +
                firstMsg +
                "\\\"," +
                "\\\"keyword1\\\": \\\""
                + vo.getUserName()
                + "\\\",\\\"keyword2\\\": \\\""
                + obeVo.getAppointmentDoctorName()
                + "\\\",\\\"keyword3\\\": \\\""
                + jsonObject.getString("help_detail")
                + "\\\",\\\"keyword4\\\": \\\""
                + vo.getCreatedTime()
                + "\\\",\\\"keyword5\\\": \\\""
                +vo.getOrderNo()
                + "\\\",\\\"remark\\\": \\\"" +
                remark
                + "\\\"}\"}";
        logger.info("sendMsgToUser ->yyt.message.msg.template.send求助订单待缴费通知消息推送入参："+JSON.toJSONString(messageContent));
        Response messageResponse = MessageService.callHumpFromInternal(method, messageContent);
        logger.info("sendMsgToUser ->yyt.message.msg.template.send求助订单待缴费通知消息推送出参："+JSON.toJSONString(messageResponse));
        if (!"0".equals(messageResponse.getResultCode())){
            logger.info("sendBoneMsgCancelOrder  发送取消订单消息失败");
        }else {
            logger.info("sendBoneMsgCancelOrder  发送取消订单消息成功");
        }

        //待缴费短信通知
        Map<String, String> msgContent = new HashMap<>();
        msgContent.put("user_name",vo.getUserName());
        Map<String,Object> pushMap = new HashMap<>();
        pushMap.put("to_user", vo.getUserMobile());
        pushMap.put("msg_type", 98);
        pushMap.put("msg_content",msgContent);
        String dataJson = JSON.toJSONString(pushMap);
        // 发送短信给患者
        logger.info("发送短信给患者，参数: " + dataJson);
        MessageService.callUnderlineFromInternal("yyt.message.msg.sms.send", dataJson);
    }
}
